package com.base.string;

/**
 * 273. 整数转换英文表示
 *
 * 将非负整数 num 转换为其对应的英文表示
 * 0 <= num <= 2^31 - 1
 * @author leon
 * @date 2021年10月11日 13:53
 */
public class NumberToWords {
    String[] singles = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    String[] teens = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    String[] thousands = {"", "Thousand", "Million", "Billion"};

    public String numberToWords(int num){
        if (num<0){
            throw  new RuntimeException("数据小于0");
        }
        if (num==0){
            return "Zero";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 3,unit = 1000000000; i >=0 ; i--,unit/=1000) {
            // 获取前三位
            int cur = num/unit;
            // 剪掉高位
            num-=cur*unit;

            if (cur!=0){
                sb.append(toEnglish(cur)).append(thousands[i]).append(" ");
            }

        }

        return sb.toString().trim();
    }

    // 实现0-999内的数据转换
    public String toEnglish(int num) {
        StringBuffer curr = new StringBuffer();
        int hundred = num / 100;
        num %= 100;
        if (hundred != 0) {
            curr.append(singles[hundred]).append(" Hundred ");
        }
        int ten = num / 10;
        if (ten >= 2) {
            curr.append(tens[ten]).append(" ");
            num %= 10;
        }
        if (num > 0 && num < 10) {
            curr.append(singles[num]).append(" ");
        } else if (num >= 10) {
            curr.append(teens[num - 10]).append(" ");
        }
        return curr.toString();
    }


}
